<?php
/**
 * Created by PhpStorm.
 * User: Chris
 * Date: 14/12/14
 * Time: 下午9:17
 */
class Controller_Mobile_Login extends Controller_Mobile_Base{



    /**
     * 登录
     */
    public function action_index(){
        if ($this->get_uid(false)!=null){
            Response::redirect( Uri::create('/mobile/user') );
        }
        $data= array();

        $userInfoResponse = Session::get(SESSION_WEIXION);
        if ($userInfoResponse){
            $data['weixinUserInfo'] = $userInfoResponse;
            // try to login with the weixin channel
        }

        if (Input::method()=='POST'){
            $account = Input::param('account');
            $password = Input::param('password');

            $channel = null ;
            if ( strstr($account, "@") ){
                $channel = Model_UserChannel::CHANNEL_EMAIL;
            }else{
                $channel = Model_UserChannel::CHANNEL_MOBILE;
            }

            $userChannel = Model_UserChannel::find('first', array(
                'where'=>array(
                    'channel'=> $channel,
                    'auth_id'=> $account
                )
            ));
//            echo $channel;exit;

            if ($userChannel){
                $user = $userChannel->user;
            }
            if ($userChannel && isset($user)
                && UserService::isPasswordMatch($password, $userChannel->auth_secret) ){
                if ($user->status==Model_User::STATUS_VALID){

                    $this->handle_user_login($user);

//                    $nextUrl = Cookie::get('BEFORE_LOGIN_URL', Uri::create('mobile/user') );
                    $nextUrl = $this->getParamNextUrl();
//                    Cookie::delete('BEFORE_LOGIN_URL');
                    Response::redirect( $nextUrl );

                    return;
                }else if ($user->status==Model_User::STATUS_PENDING) {
                    Session::set_flash("error", "帐号未激活");
                }else{
                    Session::set_flash("error", "帐号状态被禁用");
                }
            }else{
                Session::set_flash("error", "密码不正确");
            }
        }
        $this->template->content = View::forge('mobile/login', $data);
    }


    protected function getParamNextUrl(){
        $nextUrl = Input::param('nextUrl', Uri::create('mobile/user'));
        if ($nextUrl==''){
            $nextUrl = Uri::create('mobile/user');
        }
        return $nextUrl;
    }

    // 使用微信登录，进行跳转
    public function action_weixin(){
        // check if user has been bind our session
        $user_id = $this->get_uid(false);
        if ($user_id){
            // already login
            Response::redirect( Uri::create('mobile/') );
        }

//        echo "11";exit;
        // get weixin session
        $userInfoResponse = Session::get(SESSION_WEIXION);
        if ($userInfoResponse){
            // we've got the weixin session from the weixin channel
            $userChannel = Model_UserChannel::findByAuthIdNChannel($userInfoResponse->openid,
                Model_UserChannel::CHANNEL_WEIXIN);
            if ($userChannel){
                // set the user session
                $user = $userChannel->user;
                $this->handle_user_login($user);

                $nextUrl = $this->getParamNextUrl();

                Response::redirect( $nextUrl );
            }else{
                // weixin session never register, ask user register or bind account
                Response::redirect( Uri::create('/mobile/login') );
            }
            return;
        }

        $nextPage = Uri::create('mobile/login');
//        $loginRedirectUrl = Uri::create('channel/wxchannel/requireLogin?scope=snsapi_base&nextPage=') .
        $loginRedirectUrl = Uri::create('channel/wxchannel/requireLogin?scope=sns_userinfo&nextPage=') .
            urlencode($nextPage);
        Response::redirect($loginRedirectUrl);
    }


    // 对已登录微信的用户进行帐号绑定
    public function action_weixinBindAccount(){
        $user_id = $this->get_uid(false);
        if ($user_id){
            // already login
            Response::redirect( Uri::create('mobile/login') );
        }

        $weixinUserInfo = Session::get(SESSION_WEIXION);
        if (!$weixinUserInfo){
            $redirectUrl = Uri::create('mobile/login/loginByWeixin?nextPage=')
                . urlencode( Uri::create('mobile/login/weixinBindAccount') );
            Response::redirect($redirectUrl);
            return ;
        }

        $data['weixinUserInfo'] = $weixinUserInfo;
        if ( Input::method()=='POST' ){
            $account = Input::param('account');
            $password = Input::param('password');
            $channel = null ;
            if ( strstr($account, "@") ){
                $channel = Model_UserChannel::CHANNEL_EMAIL;
            }else{
                $channel = Model_UserChannel::CHANNEL_MOBILE;
            }

            $loginChannel = Model_UserChannel::find('first', array(
                'where'=>array(
                    'channel'=> $channel,
                    'auth_id'=> $account
                )
            ));

            if ($loginChannel){
                $isPasswordMatch = UserService::isPasswordMatch($password, $loginChannel->auth_secret);
                $user =$loginChannel->user;
                if ($isPasswordMatch){
                    // check if the user has been bind another weixin account
                    $existsChannel = Model_UserChannel::findByUserIdNChannel($user->id,
                        Model_UserChannel::CHANNEL_WEIXIN );
                    if ($existsChannel){
                        Session::set_flash("error", "该帐号已被绑定！");
                    }else{
                        UserService::userAddWeixinChannel($user->id, $weixinUserInfo);
                        $this->handle_user_login($user);
                        Session::set_flash("success", "成功绑定微信帐号");
                        Response::redirect(Uri::create('mobile/user'));
                        return;
                    }
                }else{
                    Session::set_flash("error", "密码错误");
                }
            }else{
                Session::set_flash("error", "不存在该登录帐号");
            }
        }

        $this->template->content = View::forge('mobile/weixinBindAccount', $data);
    }

}